const Address = require('../models/addressModel');
const { success, error, serverError, notFound, badRequest } = require('../utils/response');
const { logAudit } = require('../utils/auditLogger');
const { getLogger } = require('../logger');
const logger = getLogger('controllers.addressController');
const { validateRequired, validateId, validateArray, validateMobile } = require('../utils/validator');

// 获取地址列表
const getAddressList = async (req, res) => {
    try {
        const page = parseInt(req.query.page) || 1;
        const limit = parseInt(req.query.limit) || 10;
        const filters = {};

        // 从查询参数中构建过滤条件
        if (req.query.user_id) filters.user_id = req.query.user_id;
        if (req.query.entity_type) filters.entity_type = req.query.entity_type;
        if (req.query.entity_id) filters.entity_id = req.query.entity_id;
        if (req.query.address_type) filters.address_type = req.query.address_type;
        if (req.query.status !== undefined) filters.status = req.query.status;

        const [addresses, total] = await Address.getAddressList(page, limit, filters);

        await logAudit(req, { action_type: 'view', module_code: 'address', business_type: 'list', operation_desc: 'list' });
        success(req, res, '获取地址列表成功', {
            data: addresses,
            pagination: {
                page,
                limit,
                total,
                pages: Math.ceil(total / limit)
            }
        });
    } catch (err) {
        logger.error('获取地址列表错误', { error: err });
        serverError(req, res, '获取地址列表失败');
    }
};

// 获取地址详情
const getAddress = async (req, res) => {
    const { id } = req.params;
    try {
        if (!validateId(id)) {
            return badRequest(req, res, '地址ID格式错误');
        }

        const address = await Address.findById(id);
        if (!address) {
            return notFound(req, res, '地址不存在');
        }

        await logAudit(req, { action_type: 'view', module_code: 'address', business_type: 'detail', operation_desc: 'detail', target_entity_type: 'address', target_entity_id: id });
        success(req, res, '获取地址详情成功', address);
    } catch (err) {
        logger.error('获取地址详情错误', { error: err, id });
        serverError(req, res, '获取地址详情失败');
    }
};

// 创建地址
const createAddress = async (req, res) => {
    const { 
        user_id, entity_type, entity_id,
        province_id, city_id, district_id, street_id,
        detail_address, postal_code,
        recipient_name, recipient_phone, recipient_email,
        address_type, address_tag, is_default
    } = req.body;

    try {
        // 输入验证
        const requiredValidation = validateRequired(req.body, [
            'province_id', 'city_id', 'district_id', 'detail_address',
            'recipient_name', 'recipient_phone'
        ]);
        if (!requiredValidation.isValid) {
            return badRequest(req, res, requiredValidation.message);
        }

        // 手机号验证
        if (!validateMobile(recipient_phone)) {
            return badRequest(req, res, '手机号格式错误');
        }

        // 构建地址数据
        const addressData = {
            user_id: user_id || null,
            entity_type: entity_type || 1, // 默认关联用户
            entity_id: entity_id || null,
            province_id,
            city_id,
            district_id,
            street_id: street_id || null,
            detail_address,
            postal_code: postal_code || '',
            location_point: null, // 暂时不处理地理坐标
            recipient_name,
            recipient_phone,
            recipient_email: recipient_email || '',
            address_type: address_type || 1, // 默认家庭地址
            address_tag: address_tag || '',
            is_default: is_default || 0,
            status: 1, // 默认正常状态
            is_verified: 0,
            created_by: req.user?.id || null
        };

        const addressId = await Address.create(addressData);
        
        // 获取创建后的地址详情
        const newAddress = await Address.findById(addressId);
        
        await logAudit(req, { action_type: 'create', module_code: 'address', business_type: 'address', operation_desc: 'create', target_entity_type: 'address', target_entity_id: addressId, after_data: newAddress });
        success(req, res, '地址创建成功', newAddress);
    } catch (err) {
        logger.error('创建地址错误', { error: err, body: req.body });
        serverError(req, res, '创建地址失败');
    }
};

// 更新地址
const updateAddress = async (req, res) => {
    const { id } = req.params;
    const {
        user_id, entity_type, entity_id,
        province_id, city_id, district_id, street_id,
        detail_address, postal_code,
        recipient_name, recipient_phone, recipient_email,
        address_type, address_tag, is_default,
        status, is_verified
    } = req.body;

    try {
        if (!validateId(id)) {
            return badRequest(req, res, '地址ID格式错误');
        }

        // 检查地址是否存在
        const existingAddress = await Address.findById(id);
        if (!existingAddress) {
            return notFound(req, res, '地址不存在');
        }

        // 手机号验证
        if (recipient_phone && !validateMobile(recipient_phone)) {
            return badRequest(req, res, '手机号格式错误');
        }

        // 构建更新数据
        const updateData = {
            updated_by: req.user?.id || null
        };

        // 只更新提供的字段
        if (user_id !== undefined) updateData.user_id = user_id;
        if (entity_type !== undefined) updateData.entity_type = entity_type;
        if (entity_id !== undefined) updateData.entity_id = entity_id;
        if (province_id !== undefined) updateData.province_id = province_id;
        if (city_id !== undefined) updateData.city_id = city_id;
        if (district_id !== undefined) updateData.district_id = district_id;
        if (street_id !== undefined) updateData.street_id = street_id;
        if (detail_address !== undefined) updateData.detail_address = detail_address;
        if (postal_code !== undefined) updateData.postal_code = postal_code;
        if (recipient_name !== undefined) updateData.recipient_name = recipient_name;
        if (recipient_phone !== undefined) updateData.recipient_phone = recipient_phone;
        if (recipient_email !== undefined) updateData.recipient_email = recipient_email;
        if (address_type !== undefined) updateData.address_type = address_type;
        if (address_tag !== undefined) updateData.address_tag = address_tag;
        if (is_default !== undefined) updateData.is_default = is_default;
        if (status !== undefined) updateData.status = status;
        if (is_verified !== undefined) updateData.is_verified = is_verified;

        const success = await Address.update(id, updateData);
        
        if (success) {
            // 获取更新后的地址详情
            const updatedAddress = await Address.findById(id);
            await logAudit(req, { action_type: 'update', module_code: 'address', business_type: 'address', operation_desc: 'update', target_entity_type: 'address', target_entity_id: id, after_data: updatedAddress });
            success(req, res, '地址更新成功', updatedAddress);
        } else {
            serverError(req, res, '地址更新失败');
        }
    } catch (err) {
        logger.error('更新地址错误', { error: err, id, body: req.body });
        serverError(req, res, '更新地址失败');
    }
};

// 删除地址
const deleteAddress = async (req, res) => {
    const { id } = req.params;
    try {
        if (!validateId(id)) {
            return badRequest(req, res, '地址ID格式错误');
        }

        const success = await Address.delete(id, req.user?.id || null);
        
        if (success) {
            await logAudit(req, { action_type: 'delete', module_code: 'address', business_type: 'address', operation_desc: 'delete', target_entity_type: 'address', target_entity_id: id });
            success(req, res, '地址删除成功');
        } else {
            notFound(req, res, '地址不存在或已被删除');
        }
    } catch (err) {
        logger.error('删除地址错误', { error: err, id });
        serverError(req, res, '删除地址失败');
    }
};

// 批量删除地址
const deleteBatchAddresses = async (req, res) => {
    const { ids } = req.body;
    try {
        // 验证IDs数组
        if (!ids || !Array.isArray(ids) || ids.length === 0) {
            return badRequest(req, res, '请提供有效的地址ID数组');
        }

        // 验证每个ID格式
        const invalidIds = ids.filter(id => !validateId(id));
        if (invalidIds.length > 0) {
            return badRequest(req, res, `以下地址ID格式错误: ${invalidIds.join(', ')}`);
        }

        const affectedCount = await Address.deleteBatch(ids, req.user?.id || null);
        
        success(req, res, `成功删除 ${affectedCount} 个地址`);
    } catch (err) {
        logger.error('批量删除地址错误', { error: err, ids: req.body.ids });
        serverError(req, res, '批量删除地址失败');
    }
};

// 获取默认地址
const getDefaultAddress = async (req, res) => {
    const { user_id, address_type } = req.query;
    try {
        if (!user_id) {
            return badRequest(req, res, '请提供用户ID');
        }

        const defaultAddress = await Address.getDefaultAddress(user_id, address_type);
        
        if (defaultAddress) {
            success(req, res, '获取默认地址成功', defaultAddress);
        } else {
            success(req, res, '未找到默认地址', null);
        }
    } catch (err) {
        logger.error('获取默认地址错误', { error: err, user_id, address_type });
        serverError(req, res, '获取默认地址失败');
    }
};

// 设置默认地址
const setDefaultAddress = async (req, res) => {
    const { id } = req.params;
    try {
        if (!validateId(id)) {
            return badRequest(req, res, '地址ID格式错误');
        }

        // 检查地址是否存在
        const existingAddress = await Address.findById(id);
        if (!existingAddress) {
            return notFound(req, res, '地址不存在');
        }

        // 更新为默认地址
        const success = await Address.update(id, {
            is_default: 1,
            updated_by: req.user?.id || null
        });
        
        if (success) {
            success(req, res, '设置默认地址成功');
        } else {
            serverError(req, res, '设置默认地址失败');
        }
    } catch (err) {
        logger.error('设置默认地址错误', { error: err, id });
        serverError(req, res, '设置默认地址失败');
    }
};




// 获取省份列表
const getProvinceList = async (req, res) => {
    try {
        const provinces = await Address.getProvinceList();
        success(req, res, '获取省份列表成功', provinces);
    } catch (err) {
        logger.error('获取省份列表错误', { error: err });
        serverError(req, res, '获取省份列表失败');
    }
};

// 获取城市列表
const getCityList = async (req, res) => {
    const { provinceId } = req.params;
    try {
        if (!validateId(provinceId)) {
            return badRequest(req, res, '省份ID格式错误');
        }

        const cities = await Address.getCityList(provinceId);
        success(req, res, '获取城市列表成功', cities);
    } catch (err) {
        logger.error('获取城市列表错误', { error: err, provinceId });
        serverError(req, res, '获取城市列表失败');
    }
};

// 获取区县列表
const getDistrictList = async (req, res) => {
    const { cityId } = req.params;
    try {
        if (!validateId(cityId)) {
            return badRequest(req, res, '城市ID格式错误');
        }

        const districts = await Address.getDistrictList(cityId);
        success(req, res, '获取区县列表成功', districts);
    } catch (err) {
        logger.error('获取区县列表错误', { error: err, cityId });
        serverError(req, res, '获取区县列表失败');
    }
};

// 通过省市区ID字符串获取嵌套地址数据
const getNestedAddressByIdString = async (req, res) => {
    try {
        const { ids } = req.query;
        if (!ids || typeof ids !== 'string') {
            return badRequest(req, res, '请提供有效的ID字符串，格式如："5,28,341"');
        }

        const nestedAddress = await Address.getNestedAddressByStringIds(ids);
        if (!nestedAddress) {
            return notFound(req, res, '未找到对应的省市区信息');
        }

        success(req, res, '获取嵌套地址数据成功', nestedAddress);
    } catch (err) {
        logger.error('获取嵌套地址数据错误', { error: err });
        if (err.message.includes('ID字符串')) {
            badRequest(req, res, err.message);
        } else {
            serverError(req, res, '获取嵌套地址数据失败');
        }
    }
};

module.exports = {
    getAddressList,
    getAddress,
    createAddress,
    updateAddress,
    deleteAddress,
    deleteBatchAddresses,
    getDefaultAddress,
    setDefaultAddress,
    getProvinceList,
    getCityList,
    getDistrictList,
    getNestedAddressByIdString
};